package com.studentmanagement.ui;

import com.studentmanagement.model.Course;
import com.studentmanagement.service.CourseService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;

public class CourseManagementPanel extends JPanel {
    private CourseService courseService;
    private JTable courseTable;
    private DefaultTableModel tableModel;
    private JButton addButton;
    private JButton editButton;
    private JButton deleteButton;
    private JButton refreshButton;
    private JTextField searchField;
    private JTextField departmentField;
    private JButton searchButton;

    public CourseManagementPanel() {
        courseService = new CourseService();
        initComponents();
        setupLayout();
        setupListeners();
        loadCourseData();
    }

    private void initComponents() {
        // 表格列名
        String[] columnNames = {"ID", "课程代码", "课程名称", "学分", "授课教师", "开课院系", "教室"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        courseTable = new JTable(tableModel);
        courseTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        courseTable.getTableHeader().setReorderingAllowed(false);
        
        // 按钮初始化
        addButton = new JButton("添加");
        editButton = new JButton("编辑");
        deleteButton = new JButton("删除");
        refreshButton = new JButton("刷新");
        searchField = new JTextField(15);
        departmentField = new JTextField(15);
        searchButton = new JButton("搜索");
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 搜索区域
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchPanel.add(new JLabel("课程名称:"));
        searchPanel.add(searchField);
        searchPanel.add(new JLabel("开课院系:"));
        searchPanel.add(departmentField);
        searchPanel.add(searchButton);

        // 按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(refreshButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(addButton);

        // 北边区域组合搜索和按钮
        JPanel northPanel = new JPanel(new BorderLayout());
        northPanel.add(searchPanel, BorderLayout.WEST);
        northPanel.add(buttonPanel, BorderLayout.EAST);

        // 添加组件到主面板
        add(northPanel, BorderLayout.NORTH);
        add(new JScrollPane(courseTable), BorderLayout.CENTER);
    }

    private void setupListeners() {
        addButton.addActionListener(this::onAdd);
        editButton.addActionListener(this::onEdit);
        deleteButton.addActionListener(this::onDelete);
        refreshButton.addActionListener(e -> loadCourseData());
        searchButton.addActionListener(e -> searchCourses());
    }

    private void loadCourseData() {
        tableModel.setRowCount(0); // 清空表格
        List<Course> courses = courseService.getAllCourses();
        for (Course course : courses) {
            Object[] rowData = {
                course.getId(),
                course.getCourseCode(),
                course.getName(),
                course.getCredits(),
                "暂无", // 暂时使用固定文本代替教师名称
                course.getDepartment(),
                course.getClassroom()
            };
            tableModel.addRow(rowData);
        }
    }

    private void searchCourses() {
        String keyword = searchField.getText().trim();
        String department = departmentField.getText().trim();
        
        tableModel.setRowCount(0);
        List<Course> courses = courseService.searchCourses(keyword, department, null);
        for (Course course : courses) {
            Object[] rowData = {
                course.getId(),
                course.getCourseCode(),
                course.getName(),
                course.getCredits(),
                course.getTeacherName() != null ? course.getTeacherName() : "暂无",
                course.getDepartment(),
                course.getClassroom()
            };
            tableModel.addRow(rowData);
        }
    }

    private void onAdd(ActionEvent e) {
        CourseEditDialog dialog = new CourseEditDialog(null);
        dialog.setVisible(true);
        if (dialog.isSaved()) {
            loadCourseData();
        }
    }

    private void onEdit(ActionEvent e) {
        int selectedRow = courseTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个课程！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        Integer courseId = (Integer) tableModel.getValueAt(selectedRow, 0);
        Course course = courseService.getCourseById(courseId);
        if (course != null) {
            CourseEditDialog dialog = new CourseEditDialog(course);
            dialog.setVisible(true);
            if (dialog.isSaved()) {
                loadCourseData();
            }
        }
    }

    private void onDelete(ActionEvent e) {
        int selectedRow = courseTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个课程！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        int confirm = JOptionPane.showConfirmDialog(this, "确认删除所选课程吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            Integer courseId = (Integer) tableModel.getValueAt(selectedRow, 0);
            boolean success = courseService.deleteCourse(courseId);
            if (success) {
                loadCourseData();
                JOptionPane.showMessageDialog(this, "删除成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
} 